<?php

class ArticleTag extends ORM_Table {
    static protected $table_name = 'article_tag';
    
    static public function getTableName($params = null) {
        //$table_name = self::$table_name.substr($params['article_type_id'], 0, 1);
        return self::$table_name;
    }
    
    static public function deleteWithArticle($articleid) {
        $conn = ConnectionManager::getConn();
        $conn->delete(self::$table_name, 'article_id = '.$articleid);
    }
    
    static public function getUseTagArticle($tag, $limit = null, $order = 'created_at DESC') {
        if (!$conn_s = self::$conn) {
            $conn_s = parent::$conn;
        }
        $conn = ConnectionManager::getConn($conn_s);
        if ($limit) {
            $limit = 'LIMIT '.$limit;
        }
        if ($order) {
            $order = 'ORDER BY '.$order;
        }
        $tag_id = $conn->query("SELECT id FROM {#prefix#}".Tag::getTableName()." WHERE name = ? LIMIT 1", array($tag))->fetch();
        $article_tag = $conn->query("SELECT article_id FROM {#prefix#}".self::$table_name." WHERE tag_id = ? $order $limit", array($tag_id['id']))->fetchAll();
        foreach ($article_tag as $article_id) {
            $id[] = $article_id['article_id'];
        }
        
        return $id;
    }
    
    static public function getUseTagCount($tag) {
        if (!$conn_s = self::$conn) {
            $conn_s = parent::$conn;
        }
        $conn = ConnectionManager::getConn($conn_s);
        $tag_id = $conn->query("SELECT id FROM {#prefix#}".Tag::getTableName()." WHERE name = ? LIMIT 1", array($tag))->fetch();
        $count = $conn->query("SELECT count(*) FROM {#prefix#}".self::$table_name." WHERE tag_id = ? $limit", array($tag_id['id']))->fetchColumn();
        return $count;
    }
    
}

